extends Node2D
@onready var new_save: Button = $CanvasLayer/Panel/VBoxContainer/HBoxContainer/NewSave
@onready var save: Button = $CanvasLayer/Panel/VBoxContainer/HBoxContainer/Save
@onready var open: Button = $CanvasLayer/Panel/VBoxContainer/HBoxContainer/Open
@onready var x: TextEdit = $CanvasLayer/Panel/VBoxContainer/HBoxContainer2/X
@onready var y: TextEdit = $CanvasLayer/Panel/VBoxContainer/HBoxContainer2/Y
@onready var set_current_type : Button = $"CanvasLayer/Panel/VBoxContainer/0"
@onready var refresh: Button = $CanvasLayer/Panel/VBoxContainer/HBoxContainer2/Refresh
@onready var select_window: Panel = $CanvasLayer/SelectWindow
@onready var on_select: TextureButton = $CanvasLayer/Panel/VBoxContainer/NextLevel/OnSelect
@onready var check_button: CheckButton = $CanvasLayer/Panel/VBoxContainer/CheckButton

const DESIGN_GRID = preload("res://grid/design/design_grid.tscn")

var design_grid
var current_type : GlobelEnum.CellType
var current_index : int = -1
var sw_pre = preload("res://tools/select_window.tscn").instantiate()
var current_file
func _ready() -> void:
	design_grid = DESIGN_GRID.instantiate()
	add_child(design_grid)
	save.button_up.connect(_save_grid)
	open.button_up.connect(_open_select)
	new_save.button_up.connect(_new_save)
	set_current_type.button_group.pressed.connect(_set_current_type)
	refresh.button_up.connect(_on_refresh_button_up_event)
	on_select.button_up.connect(_on_select_next_level)
	check_button.toggled.connect(_on_toggled)

func _set_current_type(button: BaseButton) -> void :
	current_type = button.name.to_int() as GlobelEnum.CellType

func _save_grid() -> void :
	var save_file_name = current_file if current_file else "design_grid_data_"+uuid.as_rand_string()
	GlobelFileRw._write_file(save_file_name,design_grid._get_grid_data())

func _open_select() -> void :
	var dir = GlobelFileRw._get_folder_list()
	if not dir : return
	await select_window._init_data_sync(dir)
	_open_grid(select_window._get_result())
	current_file = select_window._get_result()
	print(current_file)

func _new_save() -> void :
	var size_xy = design_grid.grid_xy
	design_grid.queue_free()
	design_grid = DESIGN_GRID.instantiate()
	design_grid.grid_xy = size_xy
	add_child(design_grid)

func _on_select_next_level() -> void :
	var dir = GlobelFileRw._get_folder_list()
	if not dir : return
	await select_window._init_data_sync(dir)
	print(select_window._get_result())

func _on_refresh_button_up_event() -> void :
	design_grid.queue_free()
	design_grid = DESIGN_GRID.instantiate()
	design_grid.grid_xy = Vector2(x.text.to_int(),y.text.to_int())
	add_child(design_grid)

func _open_grid(file_name : String) -> void :
	var data = GlobelFileRw._read_file(file_name)
	design_grid.queue_free()
	design_grid = DESIGN_GRID.instantiate()
	design_grid.grid_xy = data.grid_xy
	design_grid.cells = data.cells
	add_child(design_grid)

func _on_toggled(value : bool):
	design_grid.is_need_back = value
